package com.example.demo.utils;

import com.example.demo.common.ErrorCode;
import com.example.demo.constant.SignUpConstant;
import com.example.demo.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;

public class FileUtils {

    /**
     * 验证文件
     */
    public static void validateFile(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件不能为空");
        }

        // 验证文件大小
        if (file.getSize() > SignUpConstant.MAX_FILE_SIZE) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小不能超过10MB");
        }

        // 验证文件格式
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isBlank(originalFilename)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件名不能为空");
        }
        
        String extension = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        if (!Arrays.asList(SignUpConstant.ALLOWED_FILE_EXTENSIONS).contains(extension)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "仅支持PDF和Word文档格式");
        }
    }
} 